/*
 * Copyright 2017-2101 Innel.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hykj.xxltest.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import com.hykj.xxltest.base.AppBack;
import com.hykj.xxltest.base.MsgException;
import com.hykj.xxltest.base.RequiresRole;
import com.hykj.xxltest.model.UserModel;
import com.hykj.xxltest.model.UserVerifyModel;
import com.hykj.xxltest.service.UserService;
import com.hykj.xxltest.service.UserVerifyService;
import com.hykj.xxltest.utils.HttpUtil;
import com.hykj.xxltest.utils.InnelUtil;
import com.hykj.xxltest.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户
 *
 * @author innel
 * @email 2638086622@qq.com
 * @date 2018-02-28 13:32:27
 */
@Controller
@RequestMapping("/user")
@Api(description = "用户")
public class UserController {

    private static Logger logger = Logger.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private UserVerifyService userVerifyService;


    /**
     * 登录
     */
    @RequestMapping("/login")
    @ResponseBody
    @ApiOperation(
            value = "登录",
            notes = "备注：",
            httpMethod = "POST")
    public AppBack login(@RequestParam String phone,
                         @RequestParam String password) {
        if (StringUtil.isEmpty(phone) || StringUtil.isEmpty(password)) {
            return new AppBack(-1, "必填信息不能为空");
        }
        Map condition = new HashMap();
        condition.put("phone", phone);
        condition.put("password", password);

        List<UserModel> list = userService.getListLite(condition);
        if (list.size() == 0) {
            return new AppBack(-1, "用户名或密码错误");
        }
        UserModel userModel = list.get(0);
        if (userModel.getStatus() != 0) {
            return new AppBack(-1, "用户被冻结");
        }
        String token = TokenUtil.getInstance().generateTokenUUID();
        UserModel newUser = new UserModel();
        newUser.setId(userModel.getId());
        newUser.setToken(token);
        userService.update(newUser);
        AppBack appBack = new AppBack()
                .add("user", userModel)
                .add("token", token);
        return appBack;
    }

    /**
     * 登录
     */
    @RequestMapping("/loginByPhone")
    @ResponseBody
    @ApiOperation(
            value = "验证码登录",
            notes = "备注：",
            httpMethod = "POST")
    public AppBack loginByPhone(@RequestParam String phone,
                                @RequestParam String code) {
        if (StringUtil.isEmpty(phone) || StringUtil.isEmpty(code)) {
            return new AppBack(-1, "必填信息不能为空");
        }

        Map condition = new HashMap();
        condition.put("phone", phone);

        List<UserModel> list = userService.getListLite(condition);
        if (list.size() == 0) {
            return new AppBack(-1, "用户不存在");
        }

        condition = new HashMap();
        condition.put("phone", phone);
        condition.put("code", code);
        List<UserVerifyModel> verifyList = userVerifyService.getListLite(condition);
        if (verifyList.size() == 0) {
            return new AppBack(-1, "验证码错误");
        }

        UserModel userModel = list.get(0);
        if (userModel.getStatus() != 0) {
            return new AppBack(-1, "用户被冻结");
        }
        String token = TokenUtil.getInstance().generateTokenUUID();
        UserModel newUser = new UserModel();
        newUser.setId(userModel.getId());
        newUser.setToken(token);
        userService.update(newUser);
        AppBack appBack = new AppBack()
                .add("user", userModel)
                .add("token", token);
        return appBack;
    }


    /**
     * 注册
     */
    @RequestMapping("/register")
    @ResponseBody
    @ApiOperation(
            value = "注册",
            notes = "备注：",
            httpMethod = "POST")
    public AppBack register(@RequestParam String phone,
                            @RequestParam String code,
                            @RequestParam String password) {
        if (StringUtil.isEmpty(phone) || StringUtil.isEmpty(password) || StringUtil.isEmpty(code)) {
            return new AppBack(-1, "必填信息不能为空");
        }
        if (password.length() < 6 || password.length() > 20) {
            return new AppBack(-1, "密码不合法");
        }
        Map conditon = new HashMap();
        conditon.put("phone", phone);
        List<UserModel> list = userService.getListLite(conditon);
        if (list.size() > 0) {
            throw new MsgException("已注册");
        }

        Map condition = new HashMap();
        condition.put("phone", phone);
        condition.put("code", code);
        List<UserVerifyModel> verifyList = userVerifyService.getListLite(condition);
        if (verifyList.size() == 0) {
            return new AppBack(-1, "验证码错误");
        }

        UserModel newUser = new UserModel();
        newUser.setPhone(phone);
        newUser.setPassword(password);
        newUser.setNickname(TokenUtil.getInstance().code("用户"));
        newUser.setPoint(0);
        newUser.setStatus(0);
        String token = TokenUtil.getInstance().generateTokenUUID();
        newUser.setToken(token);
        logger.info("xxxxxx" + JSON.toJSONString(newUser));
        userService.create(newUser);
        userVerifyService.clearnVerify(verifyList.get(0).getId());


        return new AppBack()
                .add("user", newUser)
                .add("token", token);
    }


    /**
     * 通过验证码改密码
     */
    @RequestMapping("/resetPassByCode")
    @ResponseBody
    @ApiOperation(
            value = "通过验证码改密码",
            notes = "备注：",
            httpMethod = "POST")
    public AppBack resetPassByCode(@RequestParam String phone,
                                   @RequestParam String code,
                                   @RequestParam String password) {
        if (StringUtil.isEmpty(phone) || StringUtil.isEmpty(code)) {
            return new AppBack(-1, "必填信息不能为空");
        }
        Map condition = new HashMap();
        condition.put("phone", phone);
        condition.put("code", code);
        List<UserVerifyModel> list = userVerifyService.getListLite(condition);
        if (list.size() == 0) {
            return new AppBack(-1, "验证码错误");
        }
        condition.clear();
        condition.put("phone", phone);
        List<UserModel> userList = userService.getListLite(condition);
        if (userList.size() == 0) {
            return new AppBack(-1, "该手机未注册");
        }
        UserModel userModel = userList.get(0);


        if (userModel.getStatus() != 0) {
            return new AppBack(-1, "用户被冻结");
        }
        if (password.length() < 6 || password.length() > 20) {
            return new AppBack(-1, "密码不合法");
        }
        UserModel newUser = new UserModel();
        newUser.setPassword(password);
        newUser.setId(userModel.getId());
        userService.update(newUser);

        /*************
         * 验证码一次性
         */
        userVerifyService.clearnVerify(list.get(0).getId());


        return new AppBack();
    }

    /**
     * 通过老密码改密码
     */
    @RequestMapping("/resetPassByPass")
    @ResponseBody
    @ApiOperation(
            value = "通过老密码改密码",
            notes = "备注：",
            httpMethod = "POST")
    public AppBack resetPassByPass(@RequestParam Integer userId,
                                   @RequestParam String oldPass,
                                   @RequestParam String password) {
        UserModel userModel = userService.getById(userId);

        if (!userModel.getPassword().equals(oldPass)) {
            return new AppBack(-1, "密码错误");
        }

        if (password.length() < 6 || password.length() > 20) {
            return new AppBack(-1, "密码不合法");
        }
        UserModel newUser = new UserModel();
        newUser.setPassword(password);
        newUser.setId(userModel.getId());
        userService.update(newUser);


        return new AppBack();
    }


    /**
     * 通过验证码改密码
     */
    @RequestMapping("/loginByCode")
    @ResponseBody
    @ApiOperation(
            value = "通过验证码登录",
            notes = "备注：",
            httpMethod = "POST")
    public AppBack loginByCode(@RequestParam String phone,
                               @RequestParam String code) {
        if (StringUtil.isEmpty(phone) || StringUtil.isEmpty(code)) {
            return new AppBack(-1, "必填信息不能为空");
        }
        Map condition = new HashMap();
        condition.put("phone", phone);
        List<UserModel> list = userService.getListLite(condition);
        if (list.size() == 0) {
            return new AppBack(-1, "该用户未注册");
        }

        condition = new HashMap();
        condition.put("phone", phone);
        condition.put("code", code);
        List<UserVerifyModel> verifyModelList = userVerifyService.getListLite(condition);
        if (verifyModelList.size() == 0) {
            return new AppBack(-1, "验证码错误");
        }

        /*************
         * 验证码一次性
         */
        userVerifyService.clearnVerify(list.get(0).getId());

        UserModel userModel = list.get(0);
        if (userModel.getStatus() != 0) {
            return new AppBack(-1, "用户被冻结");
        }

        String token = TokenUtil.getInstance().generateTokenUUID();
        UserModel newUser = new UserModel();
        newUser.setId(userModel.getId());
        newUser.setToken(token);
        userService.update(newUser);
        AppBack appBack = new AppBack()
                .add("user", userModel)
                .add("token", token);

        return appBack;
    }


    /**
     * 信息
     */
    @RequestMapping("/info")
    @ResponseBody
    @RequiresRole(role = "0,1")
    @ApiOperation(
            value = "获取当前资源",
            notes = "备注：",
            httpMethod = "POST")
    public AppBack info(
            @ApiParam(value = "当前资源的ID", required = true)
            @RequestParam Integer id) {
        UserModel user = userService.getByIdD(id);
        if (user == null) {
            return new AppBack(-1, "当前资源不存在");
        }
        return new AppBack(user);
    }


    /**
     * 修改
     */
    @RequestMapping("/update2")
    @ResponseBody
    @RequiresRole(role = "0")
    @ApiOperation(
            value = "前端更新用户资料",
            notes = "备注：",
            httpMethod = "POST")
    public AppBack update(@ApiParam(value = "用户名")
                          @RequestParam
                                  Integer userId,
                          @ApiParam(value = "token")
                          @RequestParam
                                  String token,
                          @ApiParam(value = "手机号")
                          @RequestParam(required = false)
                                  String phone,
                          @ApiParam(value = "昵称")
                          @RequestParam(required = false)
                                  String nickname,
                          @ApiParam(value = "头像")
                          @RequestParam(required = false)
                                  String headPhoto,
                          @ApiParam(value = "姓名")
                          @RequestParam(required = false)
                                  String realname,
                          @ApiParam(value = "生日   例1999-05-19")
                          @RequestParam(required = false)
                                  String birthday,
                          @ApiParam(value = "性别 男/女")
                          @RequestParam(required = false)
                                  String sex,
                          @ApiParam(value = "身体状态  例 健康,自然")
                          @RequestParam(required = false)
                                  String bodyTag,
                          @ApiParam(value = "期望标签 ")
                          @RequestParam(required = false)
                                  String expTag,
                          @ApiParam(value = " ")
                          @RequestParam(required = false)
                                  String email) {
        UserModel user = new UserModel();

        if (StringUtils.isNotEmpty(phone)) {
            Map conditon = new HashMap();
            conditon.put("phone", phone);
            List<UserModel> list = userService.getListLite(conditon);
            if (list.size() > 0) {
                throw new MsgException("该手机号已注册");
            }
            user.setPhone(phone);
        }
        user.setId(userId);
        user.setNickname(nickname);
        user.setHeadPhoto(headPhoto);
        user.setRealname(realname);
        user.setBirthday(birthday);
        user.setSex(sex);
        user.setBodyTag(bodyTag);
        user.setExpTag(expTag);
        user.setEmail(email);
        userService.update(user);
        return new AppBack();
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @ResponseBody
    @RequiresRole(role = "1")
    @ApiOperation(
            value = "获取列表",
            notes = "备注：",
            httpMethod = "POST")
    public AppBack list(@ApiParam(value = "每页显示个数,不填默认10")
                        @RequestParam(required = false)
                                Integer pageSize,
                        @ApiParam(value = "")
                        @RequestParam(required = false)
                                Integer id,
                        @ApiParam(value = "0正常 -1冻结 -10删除")
                        @RequestParam(required = false)
                                Integer status,
                        @ApiParam(value = "开始时间 范例 2017-11-06 16:02:11", hidden = true)
                        @RequestParam(required = false)
                                String startTime,
                        @ApiParam(value = "截止时间 格式 YYYYMMDD 也可以", hidden = true)
                        @RequestParam(required = false)
                                String endTime,
                        @ApiParam(value = "搜索关键字")
                        @RequestParam(required = false)
                                String searchKey,
                        @ApiParam(value = "是否是后台列表请求", hidden = true)
                        @RequestParam(required = false)
                                String backList,
                        @ApiParam(value = "是否简单显示", hidden = true)
                        @RequestParam(required = false)
                                String noD,
                        @ApiParam(value = "不填不分页")
                        @RequestParam(required = false)
                                Integer page) {
        Map<String, Object> params = new HashMap<>();
        params.put("pageSize", pageSize);
        params.put("id", id);
        params.put("status", status);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("searchKey", searchKey);
        params.put("noD", noD);
        params.put("backList", backList);
        if (page == null) {
            return new AppBack(userService.getDList(params));
        }
        PageInfo<UserModel> p = userService.getDList(params, page);
        return new AppBack(p);
    }


    /**
     * 修改
     */
    @RequestMapping("/update")
    @ResponseBody
    @RequiresRole(role = "1")
    @ApiOperation(
            value = "后台更新当前资源",
            notes = "备注：",
            httpMethod = "POST")
    public AppBack update(@ApiParam(value = "资源ID")
                          @RequestParam
                                  Integer id,
                          @ApiParam(value = "昵称")
                          @RequestParam(required = false)
                                  String nickname,
                          @ApiParam(value = "头像")
                          @RequestParam(required = false)
                                  String headPhoto,
                          @ApiParam(value = "token")
                          @RequestParam(required = false)
                                  String token,
                          @ApiParam(value = "0正常 -1冻结 -10删除")
                          @RequestParam(required = false)
                                  Integer status,
                          @ApiParam(value = "手机号码")
                          @RequestParam(required = false)
                                  String phone,
                          @ApiParam(value = "密码")
                          @RequestParam(required = false)
                                  String password,
                          @ApiParam(value = "姓名")
                          @RequestParam(required = false)
                                  String realname,
                          @ApiParam(value = "生日   例1999-05-19")
                          @RequestParam(required = false)
                                  String birthday,
                          @ApiParam(value = "性别 男/女")
                          @RequestParam(required = false)
                                  String sex,
                          @ApiParam(value = "身体状态  例 健康,自然")
                          @RequestParam(required = false)
                                  String bodyTag,
                          @ApiParam(value = "期望标签 ")
                          @RequestParam(required = false)
                                  String expTag,
                          @ApiParam(value = "")
                          @RequestParam(required = false)
                                  String wechatOpenid,
                          @ApiParam(value = "")
                          @RequestParam(required = false)
                                  String qqOpenid,
                          @ApiParam(value = "")
                          @RequestParam(required = false)
                                  String weboOpenid,
                          @ApiParam(value = " ")
                          @RequestParam(required = false)
                                  String email,
                          @ApiParam(value = "选填参数控制 默认不填")
                          @RequestParam(required = false)
                                  Integer searchKey) {
        UserModel user = new UserModel();
        user.setId(id);
        user.setNickname(nickname);
        user.setHeadPhoto(headPhoto);
        user.setToken(token);
        user.setStatus(status);
        user.setPhone(phone);
        user.setPassword(password);
        user.setRealname(realname);
        user.setBirthday(birthday);
        user.setSex(sex);
        user.setBodyTag(bodyTag);
        user.setExpTag(expTag);
        user.setWechatOpenid(wechatOpenid);
        user.setQqOpenid(qqOpenid);
        user.setWeboOpenid(weboOpenid);
        user.setEmail(email);
        userService.update(user);
        return new AppBack();
    }


    /**
     * 微信登录，第一次登录就注册
     */
    @RequestMapping("/wechatLogin")
    @ResponseBody
    @ApiOperation(
            value = "微信登录",
            notes = "备注：",
            httpMethod = "POST")
    public AppBack wechatLogin(@ApiParam(value = "CODE", required = true) @RequestParam String CODE) throws Exception {

        if (StringUtils.isEmpty(CODE)) {
            return new AppBack(-1, "code不能为空");
        }

        String resultx1;
        try {                             //https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxcf6d7c834cea0080&secret=665c93355fdfaf7c0c4012b1cec8ad35&grant_type=authorization_code&code=021iACot1iJunb0AGWmt1MbLot1iACoT
            resultx1 = HttpUtil.get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx0ad7fc5e019d1350&secret=355e10aef15353dde4fb49a5a4ea60c2&grant_type=authorization_code&code=" + CODE, null);
        } catch (Exception e) {
            logger.error(e);
            return new AppBack(-1, "连接微信失败");
        }
/*        微信返回格式{
            "access_token": "OezXcEiiBSKSxW0eoylIeFy2HFC4Bxv9JvC0Sgj4Px4_8TX1ci3jF_QP_6sWjvx2rCAUjXEP1_9edZdJLf3MIwii2N8cnTooDfx7nYpFRmOSZyq4gb2FNdWJr__KUqPtcfVUvg6XBTucZZ4zH6v8VQ",
                "expires_in": 7200,
                "refresh_token": "OezXcEiiBSKSxW0eoylIeFy2HFC4Bxv9JvC0Sgj4Px4_8TX1ci3jF_QP_6sWjvx2lW60INlf6AK1q21rW7mJyc5yG3GZ9p1psANOKTi2EZUQXA6CnwSXxDQlJ3421tEOvCWIrJhkA8oTqjsLKYG-yg",
                "openid": "oJekJs2faTQ47FGjDOEIyOPMN97s",
                "scope": "snsapi_login",
                "unionid": "o4wcnw02YjFUYglZxV0LwcBkVF6Y"
        }*/
        Map map1 = JSON.parseObject(resultx1, Map.class);

        if (map1.size() == 0) {
            return new AppBack(-1, "认证失败");
        }
        if (map1.get("openid") == null) {
            logger.info("空指针 " + CODE);
            logger.info(JSON.toJSON(resultx1));
            return new AppBack(-1, "认证失败");
        }

        String openid = map1.get("openid").toString();
        String access_token = map1.get("access_token").toString();
        logger.info(openid);
        logger.info(access_token);
        String resultx;
        try {
            resultx = HttpUtil.get("https://api.weixin.qq.com/sns/userinfo?openid=" + openid + "&access_token=" + access_token, null);
        } catch (Exception e) {
            logger.error(e);
            return new AppBack(-1, "连接微信失败");
        }
        logger.info(resultx);
        Map map = JSON.parseObject(resultx, Map.class);
        if (map.get("openid") == null) {
            logger.info("空指针 openid" + CODE);
            logger.info(JSON.toJSON(resultx1));
            return new AppBack(-1, "微信验证失败");
        }
        HashMap condition = new HashMap();
        condition.put("wechatOpenid", openid);
        List<UserModel> userModels = userService.getListLite(condition);
        UserModel userModel;
        if (userModels.size() == 0) {
            String nickname = map.get("nickname").toString();
            nickname = InnelUtil.filterOffUtf8Mb4(nickname);
            String headimgurl = map.get("headimgurl").toString();
            userModel = new UserModel();
            userModel.setWechatOpenid(openid);
            userModel.setNickname(nickname);
            userModel.setHeadPhoto(headimgurl);
            userModel.setPoint(0);
            userModel.setStatus(0);
            userService.create(userModel);
        } else {
            userModel = userModels.get(0);
        }

        UserModel newUser = new UserModel();
        String token = TokenUtil.getInstance().generateTokenUUID();
        newUser.setToken(token);
        newUser.setId(userModel.getId());
        userService.update(newUser);


        return new AppBack()
                .add("user", userModel)
                .add("token", token);
    }


}
